﻿<%@ WebHandler Language="C#" Class="ErpSendMESMaterialPageHandler" %>

/* Description:配套单校准
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2025.9.24
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BusinessRule.DTO;
using DatabaseAccess.DBUtility;
using System.Web.SessionState;
using Newtonsoft.Json;
using System.Collections;
using System.IO;
using System.Configuration;

public class ErpSendMESMaterialPageHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    string exportPath = ConfigurationManager.AppSettings["ExportPath"]; //导出路径
    string fileBasePath = ConfigurationManager.AppSettings["ImportPath"].ToString();//导入临时路径
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getUserInfo":
                    getUserInfo(context);
                    break;
                case "getMfgorderData":
                    getMfgorderData(context);
                    break;
                case "getBom":
                    getBom(context);
                    break;
                case "getErp":
                    getErp(context);
                    break;
                case "getDiff":
                    getDiff(context);
                    break;
                case "resendErp":
                    resendErp(context);//重推
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
        }
    }

    string getMfgorderDataSql(HttpContext context)
    {
        string sql = @"
SELECT DISTINCT mfg.mfgorderid,mfg.mfgordername,mfg.qty,mfg.plannedstartdate,pb3.productname,
       mfg.plannedcompletiondate
FROM mfgorder mfg
--查订单件号信息
LEFT JOIN productbase pb2 ON pb2.productbaseid = mfg.productbaseid
LEFT JOIN product p2 ON p2.productid = NVL(pb2.revofrcdid,mfg.productid)
LEFT JOIN productbase pb3 ON pb3.productbaseid=p2.productbaseid
--查件号默认工艺信息
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = p2.workflowbaseid
LEFT JOIN workflow wf ON wf.workflowid = NVL(wfb.revofrcdid,p2.workflowid)
INNER JOIN bom b ON b.workflowid = wf.workflowid
LEFT JOIN orderstatus od ON mfg.orderstatusid = od.orderstatusid
WHERE NVL(od.orderstatusname,'打开') <> '关闭'";
        //件号
        if (context.Request["productname"] != null && context.Request["productname"].ToString() != "")
        {
            sql += string.Format(" AND pb3.productname LIKE '%{0}%'", context.Request["productname"].ToString());
        }

        //订单号
        if (context.Request["mfgordername"] != null && context.Request["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND mfg.mfgordername LIKE '%{0}%'", context.Request["mfgordername"].ToString());
        }

        //主制分厂
        if (context.Request["factoryid"] != null && context.Request["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND mfg.factoryid = '{0}'", context.Request["factoryid"].ToString());
        }
        return sql;
    }

    void getMfgorderData(HttpContext context)
    {
        string sql = getMfgorderDataSql(context);
        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
        paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        foreach (DataColumn col in result.DBTable.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    void getBom(HttpContext context)
    {
        string sql = @"
SELECT mfg.mfgorderid,mfg.mfgordername,mfg.qty,mfg.plannedstartdate,pb3.productname mfgproductname,
       mfg.plannedcompletiondate,sb2.specname,s.specno,s.opdesc,pbn.productname,pml.qtyrequired,
       b.bomid,bb.bomname,pml.productmateriallistitemid,pml.productid,pml.qtyrequired * mfg.qty mesqty
FROM mfgorder mfg
--查订单件号信息
LEFT JOIN productbase pb2 ON pb2.productbaseid = mfg.productbaseid
LEFT JOIN product p2 ON p2.productid = NVL(pb2.revofrcdid,mfg.productid)
LEFT JOIN productbase pb3 ON pb3.productbaseid=p2.productbaseid
--查件号默认工艺信息
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = p2.workflowbaseid
LEFT JOIN workflow wf ON wf.workflowid = NVL(wfb.revofrcdid,p2.workflowid)
--bom信息
INNER JOIN bom b ON b.workflowid = wf.workflowid
LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
--bom工序信息
LEFT JOIN specbase sb ON sb.specbaseid=pml.specbaseid
LEFT JOIN spec s ON  s.specid=NVL(sb.revofrcdid, pml.specid)
LEFT JOIN specbase sb2 ON sb2.specbaseid = s.specbaseid
--子零件信息
LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid
WHERE mfg.mfgordername = '{0}'
ORDER BY s.specno";
        sql = string.Format(sql, context.Request.Form["mfgordername"].ToString());
        DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtBom.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "成功", DBTable = dtBom }));
    }

    void getErp(HttpContext context)
    {
        string sql = @"SELECT * FROM erp_send_material erp WHERE erp.mfgordername = '{0}'";
        sql = string.Format(sql, context.Request.Form["mfgordername"].ToString());
        DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtBom.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "成功", DBTable = dtBom }));
    }

    void getDiff(HttpContext context)
    {
        string mfgordername = context.Request.Form["mfgordername"].ToString();
        string sql = @"
SELECT t.id,t.specno,t.specname,t.productname,t.diffqty,t.mfgordername,
       DECODE(t.oper_type,1,'增加数量',2,'减少数量',3,'增加条目',4,'删除条目') oper_type,t.erp_return_date,t.createdate,'已推送' send_status,
       DECODE(t.erp_status,0,'失败',1,'成功') erp_status,t.erp_msg
FROM erp_mes_bom_diff t
WHERE t.mfgordername = '{0}' AND t.diff_type = 'ERP'";
        sql = string.Format(sql, mfgordername);
        DataTable dtDiff = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtDiff.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "成功", DBTable = dtDiff }));
    }

    void getUserInfo(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", ReturnData = m_UserInfo }));
        }
    }

    void resendErp(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
            return;
        }
        var dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
        string mfgordername = "";
        if (dtPostData.Rows.Count > 0)
        {
            mfgordername = dtPostData.Rows[0]["mfgordername"].ToString();
            string insertSql = string.Format("INSERT INTO mes_send_erp_diff(mfgordername,diff_type) VALUES('{0}','ERP')", mfgordername);
            int count = DatabaseHelper.ExecuteSql(insertSql);
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = count > 0, Message = "重推成功", DBTable = null }));
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "重推成功", DBTable = null }));
        }

    }
}